#!/usr/bin/env python
# -*- coding: utf-8 -*-

from odoo import models, fields, api
from odoo.exceptions import UserError, ValidationError

class QualityPoint(models.Model):
    _inherit = "quality.point"

    def check_execute_now(self):
        self.ensure_one()
        expired_point_row = self.env.ref('sb_product_expiry_ext.quality_check_expired')
        if self == expired_point_row:
            return False
        return super(QualityPoint, self).check_execute_now()

class QualityCheck(models.Model):
    _inherit = 'quality.check' 
 
    return_picking_id = fields.Many2one('stock.picking')
    batch_id = fields.Many2one('expired.quality.batch',  string='质检批次')
    lot_qty = fields.Integer('Lot QTY', compute="_get_lot_qty")
    s_scrap_qty = fields.Integer('Scrap QTY')

    @api.depends('reject_reason_ids', 'refresh_qty', 's_scrap_qty')
    def _compute_incoming_qty(self):
        for record in self:
            if record.s_scrap_qty > 0 and record.lot_id:
                record.incoming_qty = record.lot_qty - record.s_scrap_qty
            elif record.lot_id:
                record.incoming_qty = record.lot_qty
            elif record.s_scrap_qty > 0:
                record.incoming_qty = record.product_uom_qty - record.s_scrap_qty
            else:
                super()._compute_incoming_qty()

    @api.depends('lot_id')
    def _get_lot_qty(self):
        for row in self:
            row.lot_qty = row.lot_id.product_qty
            row.product_uom = row.lot_id.product_uom_id.id
 
    @api.model  
    def create(self, vals):
        check = super(QualityCheck, self).create(vals)
        #  if check.batch_id:
            #  check.batch_id.state  = 'in_progress'
        return check 

    def update_backorder_id(self):
        scrap_code = self.env.ref('sb_product_expiry_ext.stock_location_scrapped')
        self.ensure_one()
        if not self.picking_id.backorder_ids:
            return False
        self.picking_id.backorder_ids.update({
            'location_dest_id':  scrap_code.id
        })
        self.picking_id.backorder_ids.move_ids.write({
            'location_dest_id':  scrap_code.id
        })
        vals = [(0,0,{
            'product_id':x.product_id.id,
            'lot_id':x.lot_id.id,
            'quantity':self.s_scrap_qty,
            'location_id': x.location_id.id,
            'location_dest_id':  scrap_code.id
        }) for x in self.picking_id.move_ids.filtered(lambda x:x.product_uom_qty != x.quantity).move_line_ids]
        self.picking_id.backorder_ids.move_ids.update({'move_line_ids':vals})
        #  self.picking_id.backorder_ids.move_ids._action_done()
        self.picking_id.backorder_ids.button_validate()
 
    def do_pass(self):
        self.ensure_one() 
        if self.point_id == self.env.ref('sb_product_expiry_ext.quality_check_expired') and self.quality_state in ('pass', 'fail'):
            raise ValidationError(
                f"Quality check state is {self.quality_state}"
            )
        res = super(QualityCheck, self).do_pass()
        # 关联的stock.move 标记为通过，并触发回库 
        if self.point_id == self.env.ref('sb_product_expiry_ext.quality_check_expired') and self.batch_id:
            self._process_quality_result('pass')
            if self.batch_id.move_ids.filtered(lambda x:x.state not in ('done','cancel')):
                self.update_backorder_id()
                self.batch_id.state  = 'done'
        return res 
 
    def do_fail(self):
        self.ensure_one() 
        if self.point_id == self.env.ref('sb_product_expiry_ext.quality_check_expired') and self.quality_state in ('pass', 'fail'):
            raise ValidationError(
                f"Quality check state is {self.quality_state}"
            )
        res = super(QualityCheck, self).do_fail()
        if self.point_id == self.env.ref('sb_product_expiry_ext.quality_check_expired') and self.batch_id:
            self.s_scrap_qty = self.lot_qty
            self._process_quality_result('fail')
            if self.batch_id.move_ids.filtered(lambda x:x.state not in ('done','cancel')):
                self.update_backorder_id()
                self.batch_id.state  = 'done'
        return res 

 
    def _process_quality_result(self, result='pass'):
        #  for move in self.batch_id.move_ids:
        self.ensure_one()
        for move in self.move_id: 
            move.quality_state  = result 
            if move.product_uom_qty < self.s_scrap_qty:
                raise ValidationError(
                    f"scrap qty error,total is :{self.move_line_id.lot_id.product_qty}, scrap qty is:{self.s_scrap_qty}"
                )
            lot_row = move.move_line_ids.filtered(lambda x:x.lot_id == self.lot_id)
            if result == 'pass':
                if self.s_scrap_qty:
                    #  move.write({'quantity': move.lot_qty - self.s_scrap_qty})
                    # 回库逻辑：目标库位调整为可用库位 
                    lot_row.update({
                        'quantity': lot_row.quantity - self.s_scrap_qty
                    })
                #move.write({
                #    'location_dest_id':  self.env.ref('stock.stock_location_stock').id,
                #}) 
                #move.move_line_ids.update({
                #    'location_dest_id':  self.env.ref('stock.stock_location_stock').id,
                #    'quantity': move.lot_qty - self.s_scrap_qty
                #})
            else:
                # 报废逻辑：目标库位调整为废品库位 
                #  move.write({'location_dest_id':  self.env.ref('sb_product_expiry_ext.stock_location_scrapped').id})
                    #  move.write({'quantity': move.product_uom_qty - self.s_scrap_qty})
                    # 回库逻辑：目标库位调整为可用库位 
                    #  lot_row = move.move_line_ids.filtered(lambda x:x.lot_id == self.lot_id)
                lot_row.update({
                    'quantity': 0
                })
            if not self.batch_id.quality_check_ids.filtered(lambda x:x.quality_state == 'none'):
                move._action_done()
                move.lot_ids.production_date=fields.Date.today()

class QualityAlertTeam(models.Model):
    _inherit = "quality.alert.team"

    qc_check_count = fields.Integer('QC Quality Checks', compute='_compute_qc_check_count')

    def _compute_qc_check_count(self):
        qc_team_id = self.env.ref('sb_product_expiry_ext.quality_alert_qc_team0')
        check_data = self.env['quality.check']._read_group([('team_id', 'in', qc_team_id.ids), ('quality_state', '=', 'none')], ['team_id'], ['__count'])
        check_result = {team.id: count for team, count in check_data}
        for team in self:
            team.qc_check_count = check_result.get(team.id, 0)
